package com.data.datalib.util

import android.util.Base64
import com.data.datalib.ASSycBuilder
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

object ASAesUtil {
    private const val AES_NAME = "AES"

    private const val AES_MODE = "AES/CBC/PKCS5Padding"

    fun encrypt(key: String, iv: String, message: String): String {
        try {
            val cipher = Cipher.getInstance(AES_MODE)
            val secretKeySpec = SecretKeySpec(key.toByteArray(Charsets.UTF_8), AES_NAME)
            val ivParameterSpec = IvParameterSpec(iv.toByteArray(Charsets.UTF_8))
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)
            val encrypted = cipher.doFinal(message.toByteArray(Charsets.UTF_8))
            return Base64.encodeToString(encrypted, Base64.DEFAULT or Base64.NO_WRAP)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun encryptDefault(message: String): String {
        return encrypt(ASSycBuilder.aesKey, ASSycBuilder.aesIv, message)
    }

    fun decrypt(key: String, iv: String, encryptedMessage: String): String {
        try {
            val cipher = Cipher.getInstance(AES_MODE)
            val secretKeySpec = SecretKeySpec(key.toByteArray(Charsets.UTF_8), AES_NAME)
            val ivParameterSpec = IvParameterSpec(iv.toByteArray(Charsets.UTF_8))
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)
            val encryptedBytes = Base64.decode(encryptedMessage, Base64.DEFAULT or Base64.NO_WRAP)
            val decrypted = cipher.doFinal(encryptedBytes)
            return String(decrypted, Charsets.UTF_8)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }


    fun decryptDefault(encryptedMessage: String): String {
        return decrypt(ASSycBuilder.aesKey, ASSycBuilder.aesIv, encryptedMessage)
    }
}